<template>
  <div class="app-container">
    <div class="filter-container">
      
      <!-- <el-button type="primary">
        新增
      </el-button> -->
 <el-button  type="danger" @click="del">删除
          </el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row
      style="width: 100%;min-height:1000px;"
       @selection-change="handleSelectionChange"
      >
       <el-table-column
        type="selection"
        width="52">
         </el-table-column>
          <el-table-column min-width="100px" label="id">
        <template slot-scope="scope">
          <span>{{ scope.row.id}}</span>
        </template>
       </el-table-column>
      <el-table-column align="center" label="举报者id">
        <template slot-scope="scope">
           <span >{{scope.row.userId}}</span>
        </template>
      </el-table-column>
       <el-table-column align="center" label="被举报者id">
        <template slot-scope="scope">
           <span >{{scope.row.patientId}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100px" label="举报理由">
        <template slot-scope="scope">
          <span>{{ scope.row.content }}</span>
        </template>
      </el-table-column>
         <el-table-column min-width="100px" label="处理者id">
        <template slot-scope="scope">
          <span>{{ scope.row.processorId }}</span>
        </template>
      </el-table-column>
           <!-- <el-table-column min-width="100px" label="处理者昵称">
        <template slot-scope="scope">
           <span>{{ scope.row.processorName }}</span>
          
        </template>
      </el-table-column> -->

       <!-- <el-table-column min-width="100px" label="处理意见">
        <template slot-scope="scope">
            <span>{{ scope.row.dispose }}</span>
         
          <img :src="scope.row.cardBackUrl" alt=""  style="width:100%" @click="she_showImgList(scope.row)" >
        </template>
      </el-table-column> -->
  <el-table-column min-width="100px" label="状态">
        <template slot-scope="scope">
          <span>{{ scope.row.status|UserReportJ }}</span>
        </template>
      </el-table-column>
  <el-table-column min-width="100px" label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime|formateTime }}</span>
        </template>
      </el-table-column>
        <el-table-column min-width="100px" label="更新时间">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime|formateTime }}</span>
        </template>
      </el-table-column>
        <!-- <el-table-column min-width="100px" label="理时间">
        <template slot-scope="scope">
          <span>{{ scope.row.disposeTime |formateTime}}</span>
        </template>
      </el-table-column> -->

      <el-table-column align="center" label="操作" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status!='deleted'" size="mini" type="primary" @click="handleUpdate(scope.row)">详情
          </el-button>
            <!-- <el-button v-if="scope.row.status!='deleted'" size="mini" type="danger" @click="del(scope.row)">删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    </div>

<!--添加用户s-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
     
        <el-form-item label="id" prop="id" >
          <el-input v-model="temp.id" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userId" >
          <el-input v-model="temp.userId" :disabled="true"></el-input>
        </el-form-item>
         <el-form-item label="被举报者id" prop="patientId">
          <el-input v-model="temp.password" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="举报理由" prop="patientId">
          <el-input v-model="temp.content":disabled="true"></el-input>
        </el-form-item>
           <el-form-item label="处理者昵称" prop="processorName">
          <el-input v-model="temp.processorName" :disabled="true"></el-input>
        </el-form-item>
           <el-form-item label="处理意见" prop="dispose">
          <el-input v-model="temp.dispose" type="textarea" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select class="filter-item" v-model="temp.status" placeholder="Please select" :disabled="true">
            <el-option v-for="(item,index) in status_select" :key="index" :label="item.name" :value="item.val">
            </el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="temp.createTime" :disabled="true"></el-input>
        </el-form-item>
          <el-form-item label="更新时间" prop="updateTime">
          <el-input v-model="temp.updateTime" :disabled="true"></el-input>
        </el-form-item>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button  type="primary" @click="show_form">处理审核</el-button>
        <!-- <el-button v-else type="primary" @click="updateData">确定</el-button> -->
      </div>
    </el-dialog>
<!--添加用户e-->

    <el-dialog title="审核" :visible.sync="dialogPvVisible" >
      <el-form  border fit highlight-current-row style="width: 100%" v-loading="confirm_loading" :rules="rules" ref="lastForm" :model="tempForm" >
         <el-form-item label="处理意见:" prop="dispose">
          <el-input v-model="tempForm.dispose" type="textarea"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="comfirm">提交处理</el-button>
      </span>
    </el-dialog>

  <!--<PictureView v-if="pictureList" :pictureList="pictureList"></PictureView>-->
  </div>
  

</template>

<script>
import {
  fetchPv,
  updateArticle
} from '@/api/article'
import { getALLUserReport, userReportDel, editUserReport } from '@/api/user/user_report'
import Auth from '@/mock/Auth.js'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'
const log = console.log
const calendarTypeOptions = [
  { key: 'CN', display_name: 'China' },
  { key: 'US', display_name: 'USA' },
  { key: 'JP', display_name: 'Japan' },
  { key: 'EU', display_name: 'Eurozone' }
]
import PictureView from 'vue-simple-picture-preview'

// arr to obj ,such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    return {
      status_select: [
        { name: '忽略', val: 0 },
        { name: '未处理', val: 1 },
        { name: '平台人工处理', val: 2 },
        { name: '系统处理', val: 3 }
      ],
      confirm_loading: false,
      tempForm: {
        dispose: '',
        id: ''
      },
      new_temp: {
        email: '',
        password: '',
        roleIdList: '',
        status: '',
        username: ''
      },
      pictureList: null,
      limit: 10,
      page: 1,
      multipleSelection: '',
      tableKey: 0,
      list: null,
      total: 10,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      importanceOptions: [1, 2, 3],
      calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        type: '',
        status: 'published'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        dispose: { required: true, message: '请输入审核意见', trigger: 'change' },
        type: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        timestamp: [
          {
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }
        ],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ]
      },
      downloadLoading: false
    }
  },
  components: {
    PictureView
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    she_showImgList(row) {
      console.log('she_showImgList+++++++++++++++++')
      const picture_list = [row.cardBackUrl, row.cardHandheldUrl, row.cardPositiveUrl]
      this.pictureList = picture_list
    },
    detail(row) {
      row = JSON.stringify(row)
      this.$router.push({ path: '/detail_user', query: { usermsg: row, show: true }})
    },
    edit(row) {
      // row = JSON.stringify(row)
      // this.$router.push({ path: '/user_auth_detail', query: { usermsg: row, show: false }})
      this.dialogFormVisible = true
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    del: function() {
      const role_id = []
      this.multipleSelection.forEach((val, index, x) => {
        role_id.push(this.multipleSelection[index].id)
      })
      // const obj = {	roleIds: role_id }
      this.$confirm(`确定删除？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        userReportDel(role_id).then((e) => {
          this.listLoading = false
          if (e.data.code === 500) {
            this.$Message.error(e.data.msg)
          } else {
            this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        }).catch((e) => {
          this.listLoading = false
          this.$Message.error(e)
        })
      }).catch(() => {

      })
    },
    comfirm: function() {
      this.$refs['lastForm'].validate(valid => {
        if (valid) {
          this.tempForm.id = this.temp.id
          this.confirm_loading = true
          editUserReport(this.tempForm).then((e) => {
            this.confirm_loading = false

            if (e.data.code === 500) {
              this.Message.error(e.data.msg)
            } else {
              this.dialogPvVisible = false
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000,
                onClose: () => {
                  this.getList()
                }
              })
            }
          }).catch((e) => {
            this.confirm_loading = false
            this.Message.error(e)
          })
        }
      })
    },
    show_form: function() {
      this.dialogPvVisible = true
      this.resetTempFrom()
      this.$nextTick(() => {
        this.$refs['lastForm'].clearValidate()
      })
    },
    created_user: function(data) {
      this.dialogPvVisible = true
      // this.$refs['dataForm'].validate(valid => {
      //   if (valid) {
      //     CreateUser(data).then((e) => {
      //       if (e.data.code === 500) {
      //         this.Message.error(e.data.msg)
      //       } else {
      //         this.$notify({
      //           title: '成功',
      //           message: '操作成功',
      //           type: 'success',
      //           duration: 2000
      //         })
      //       }
      //     }).catch((e) => {
      //       this.Message.error(e)
      //     })
      //   }
      // })
    },
    pre() {
      this.page <= 0 ? '' : this.page -= 1
    },
    next() {
      this.page += 1
    },
    getList() {
      this.listLoading = true
      // 获取所有用户信息
      const temp_data = {
        limit: this.limit,
        page: this.page
      }
      getALLUserReport(temp_data)
        .then(res => {
        //  this.listLoading = false
          console.log('res++++++++++++++++++')
          console.log(res)
          console.log('res.data.page.list')
          console.log(res.data.page.list)
          res.data.page.list.forEach((val, index, x) => {
            res.data.page.list[index].cardBackUrl = [res.data.page.list[index].cardBackUrl]
            res.data.page.list[index].cardHandheldUrl = [res.data.page.list[index].cardHandheldUrl]
            res.data.page.list[index].cardPositiveUrl = [res.data.page.list[index].cardPositiveUrl]
          })
          // this.list = res.page

          // this.total = res.totalPage
          console.log('res.data.page.list')
          console.log(res.data.page.list)
          this.list = res.data.page.list
          this.total = res.data.totalPage
          this.listLoading = false
        })
        .catch(err => {
          this.listLoading = false
          log(err)
        })
    },
    handleFilter() {
      this.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        id: '',
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    resetTempFrom() {
      this.tempForm = {
        dispose: '',
        id: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {

    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateArticle(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = [
          'timestamp',
          'title',
          'type',
          'importance',
          'status'
        ]
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
